from django.shortcuts import render

# Create your views here.

from .models import Order
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin
from .serializer import OrderModelSerializer
from rest_framework.generics import CreateAPIView
from luffyapi.utils.response import APIResponse
from rest_framework.response import Response

from luffyapi.utils.loggers import get_logger
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
logger=get_logger()
class PayView(GenericViewSet, CreateModelMixin):
    # class PayView(ViewSetMixin,CreateAPIView):
    # 认证类，权限类
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated,]
    queryset = Order.objects.all()
    serializer_class = OrderModelSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, context={'request': request})
        # OrderModelSerializer(data=request.data,context={'request':request})
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        # serializer.save()
        pay_url = serializer.context['pay_url']
        return APIResponse(pay_url=pay_url)




#只需要继承apiview即可
from rest_framework.views import  APIView
from .models import Order
class SuccessView(APIView):
    def get(self,request,*args,**kwargs):
        # 去订单表查询该订单的状态
        out_trade_no=request.query_params.get('out_trade_no')
        # 校验这个数据是什么状态
        try:
            Order.objects.get(out_trade_no=out_trade_no,order_status=1)
            return APIResponse(msg='已经支付')
        except Exception as e:
            return APIResponse(code=101,msg='请稍后刷新该页面再看')


    def post(self,request,*args,**kwargs):
        # 支付宝回调，数据在哪？
        # 取出支付宝回调返回的数据，在request.data中
        # 验证签名
        # 修改订单状态
        # 告诉支付宝成功
        try:
            print(request.data)
            result_data = request.data.dict()
            out_trade_no = result_data.get('out_trade_no')
            signature = result_data.pop('sign')
            from luffyapi.libs import alpay
            result = alpay.alipay.verify(result_data, signature)
            if result and result_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                # 完成订单修改：订单状态、流水号、支付时间
                # Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1,trade_no=result_data.get('trade_no'),pay_time=result_data.get('timestamp'))
                Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1)
                # 完成日志记录
                logger.warning('%s订单支付成功' % out_trade_no)
                return Response('success')
            else:
                logger.error('%s订单支付失败' % out_trade_no)
        except:
            pass
        return Response('failed')



